<script lang="ts" setup>
import type {
  OnActionClickParams,
  VxeTableGridOptions,
} from '#/adapter/vxe-table';
import type { MenuItem } from '#/api/system/models';

import { onMounted } from 'vue';

import { Page, useVbenDrawer } from '@vben/common-ui';
import { IconifyIcon } from '@vben/icons';

import { Button, message, Space } from 'ant-design-vue';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { deleteMenuApi, getMenuListApi } from '#/api/system/menu';
import { $t } from '#/locales';

import { useColumns } from './data';
import Form from './modules/form.vue';

const [FormDrawer, formDrawerApi] = useVbenDrawer({
  connectedComponent: Form,
  destroyOnClose: true,
});

/**
 * 创建菜单
 */
function onCreate() {
  formDrawerApi.setData(null).open();
}

/**
 * 编辑菜单
 * @param row
 */
function onEdit(row: MenuItem) {
  formDrawerApi.setData(row).open();
}

/**
 * 删除菜单
 * @param row
 */
function onDelete(row: MenuItem) {
  const hideLoading = message.loading({
    content: $t('ui.actionMessage.deleting', [row.name]),
    duration: 0,
    key: 'action_process_msg',
  });
  deleteMenuApi(row.id)
    .then(() => {
      message.success({
        content: $t('ui.actionMessage.deleteSuccess', [row.name]),
        key: 'action_process_msg',
      });
      loadData();
    })
    .catch(() => {
      hideLoading();
    });
}

/**
 * 表格操作按钮的回调函数
 */
function onActionClick({ code, row }: OnActionClickParams<MenuItem>) {
  switch (code) {
    case 'delete': {
      onDelete(row);
      break;
    }
    case 'edit': {
      onEdit(row);
      break;
    }
  }
}

const [Grid, gridApi] = useVbenVxeGrid({
  gridOptions: {
    columns: useColumns(onActionClick),
    border: true,
    rowConfig: {
      isHover: true,
      useKey: true,
    },
    treeConfig: {
      rowField: 'id',
      parentField: 'parentId',
      transform: true,
      expandAll: true,
      showLine: true,
    },
    pagerConfig: {
      enabled: false,
    },
  } as VxeTableGridOptions,
});

/** 展开菜单 */
const expandAll = () => {
  gridApi.grid?.setAllTreeExpand(true);
};

/** 折叠菜单 */
const collapseAll = () => {
  gridApi.grid?.setAllTreeExpand(false);
};

/** 加载时间 */
async function loadData() {
  const items = await getMenuListApi();
  gridApi.grid.reloadData(items);
}

onMounted(async () => {
  await loadData();
});
</script>

<template>
  <Page auto-content-height>
    <FormDrawer class="w-[720px]" @success="loadData()" />
    <Grid>
      <template #toolbar-tools>
        <Space>
          <Button type="primary" @click="onCreate()"> 新增菜单 </Button>
          <Button type="primary" @click="expandAll"> 展开全部 </Button>
          <Button type="primary" @click="collapseAll"> 折叠全部 </Button>
        </Space>
      </template>
      <template #icon="{ row }">
        <div class="flex items-center justify-center">
          <IconifyIcon :icon="row.icon" />
        </div>
      </template>
    </Grid>
  </Page>
</template>
